"""
摄像头相关的Pydantic模式 - 简化版
Simplified Camera Pydantic Schemas
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional, List, Dict, Any
from datetime import datetime
from enum import Enum


class CameraStatus(str, Enum):
    """摄像头状态枚举"""
    ONLINE = "online"
    OFFLINE = "offline"
    ERROR = "error"
    MAINTENANCE = "maintenance"
    CREATED = "created"


class StreamStatus(str, Enum):
    """流状态枚举"""
    INACTIVE = "inactive"
    ACTIVE = "active"
    ERROR = "error"
    RECONNECTING = "reconnecting"


class CameraBase(BaseModel):
    """摄像头基础模式"""
    name: str = Field(..., min_length=1, max_length=255, description="设备名称")
    longitude: float = Field(default=0.0, ge=-180, le=180, description="经度坐标")
    latitude: float = Field(default=0.0, ge=-90, le=90, description="纬度坐标")
    height: Optional[float] = Field(default=10.0, ge=0, le=1000, description="安装高度（米）")
    location: Optional[str] = Field(default=None, max_length=255, description="安装位置描述")
    rtsp_url: Optional[str] = Field(default=None, max_length=512, description="RTSP流地址")
    wvp_device_id: Optional[str] = Field(default=None, max_length=100, description="WVP设备ID")
    wvp_channel_id: Optional[str] = Field(default=None, max_length=100, description="WVP通道ID")
    description: Optional[str] = Field(default=None, max_length=1000, description="设备详细描述")
    ai_enabled: bool = Field(default=False, description="是否启用AI分析功能")
    processing_fps: int = Field(default=3, ge=1, le=30, description="AI处理帧率")
    priority_level: int = Field(default=5, ge=1, le=10, description="处理优先级")

    @field_validator('rtsp_url')
    @classmethod
    def validate_rtsp_url(cls, v: Optional[str]) -> Optional[str]:
        """验证RTSP URL格式"""
        if v is None:
            return v
        if not v.startswith(('rtsp://', 'http://', 'https://')):
            raise ValueError('RTSP URL必须以rtsp://、http://或https://开头')
        return v

    @field_validator('name')
    @classmethod
    def validate_name(cls, v: str) -> str:
        """验证设备名称"""
        v = v.strip()
        if not v:
            raise ValueError('设备名称不能为空')
        return v


class CameraCreate(CameraBase):
    """创建摄像头请求模式"""
    pass


class CameraUpdate(BaseModel):
    """更新摄像头请求模式"""
    name: Optional[str] = Field(default=None, min_length=1, max_length=255)
    longitude: Optional[float] = Field(default=None, ge=-180, le=180)
    latitude: Optional[float] = Field(default=None, ge=-90, le=90)
    height: Optional[float] = Field(default=None, ge=0, le=1000)
    location: Optional[str] = Field(default=None, max_length=255)
    rtsp_url: Optional[str] = Field(default=None, max_length=512)
    wvp_device_id: Optional[str] = Field(default=None, max_length=100)
    wvp_channel_id: Optional[str] = Field(default=None, max_length=100)
    description: Optional[str] = Field(default=None, max_length=1000)
    ai_enabled: Optional[bool] = Field(default=None)
    status: Optional[CameraStatus] = Field(default=None)
    processing_fps: Optional[int] = Field(default=None, ge=1, le=30)
    priority_level: Optional[int] = Field(default=None, ge=1, le=10)


class CameraResponse(CameraBase):
    """摄像头响应模式"""
    id: int = Field(..., description="摄像头唯一标识符")
    status: CameraStatus = Field(..., description="摄像头当前状态")
    stream_status: StreamStatus = Field(default=StreamStatus.INACTIVE, description="视频流状态")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="最后更新时间")
    
    class Config:
        from_attributes = True


class CameraListResponse(BaseModel):
    """摄像头列表响应模式"""
    items: List[CameraResponse] = Field(..., description="摄像头列表")
    total: int = Field(..., ge=0, description="总记录数")
    page: int = Field(default=1, ge=1, description="当前页码")
    size: int = Field(default=10, ge=1, description="每页大小")


# WVP相关模式
class WVPDeviceBase(BaseModel):
    """WVP设备基础模式"""
    device_id: str = Field(..., description="设备ID")
    device_name: Optional[str] = Field(default=None, description="设备名称")
    manufacturer: Optional[str] = Field(default=None, description="制造商")
    model: Optional[str] = Field(default=None, description="设备型号")
    ip: Optional[str] = Field(default=None, description="设备IP地址")
    port: Optional[int] = Field(default=5060, description="设备端口")


class WVPDeviceCreate(WVPDeviceBase):
    """创建WVP设备请求模式"""
    pass


class WVPDeviceResponse(WVPDeviceBase):
    """WVP设备响应模式"""
    id: int = Field(..., description="数据库ID")
    status: str = Field(default="offline", description="设备状态")
    channel_count: int = Field(default=0, description="通道数量")
    register_time: Optional[datetime] = Field(default=None, description="注册时间")
    created_at: datetime = Field(..., description="创建时间")
    
    class Config:
        from_attributes = True


class WVPChannelBase(BaseModel):
    """WVP通道基础模式"""
    device_id: str = Field(..., description="设备ID")
    channel_id: str = Field(..., description="通道ID")
    channel_name: Optional[str] = Field(default=None, description="通道名称")
    longitude: float = Field(default=0.0, description="经度")
    latitude: float = Field(default=0.0, description="纬度")


class WVPChannelResponse(WVPChannelBase):
    """WVP通道响应模式"""
    id: int = Field(..., description="数据库ID")
    status: str = Field(default="offline", description="通道状态")
    created_at: datetime = Field(..., description="创建时间")
    
    class Config:
        from_attributes = True